import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:openchina/common/event_bus.dart';
import 'package:openchina/constants/constants.dart';
import 'package:openchina/models/new_list.dart';
import 'package:openchina/utils/data_util.dart';
import 'package:openchina/utils/net_util.dart';
import 'package:openchina/widgets/NewsListItemPull.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'login_web_page.dart';

class NewsListPage extends StatefulWidget {
  @override
  _NewsListPageState createState() => _NewsListPageState();
}

class _NewsListPageState extends State<NewsListPage> with AutomaticKeepAliveClientMixin{
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  List<NewList> _newsList = [];
  bool isLogin = false;
  int curPage = 1;
  bool isHasMore = false;

  _getNewsList() async {
    DataUtil.isLogin().then((isLogin) {
      if (isLogin) {
        DataUtil.getTokenAccess().then((accessToken) {
          if (accessToken != null && accessToken.length != 0) {
            Map<String, dynamic> params = new Map<String, dynamic>();
            params['access_token'] = accessToken;
            params['catalog'] = 1;
            params['page'] = curPage;
            params['pageSize'] = 10;
            params['dataType'] = AppInfo.JSON;
            NetUtil.get(AppUrls.NEWS_LIST, params).then((data) {
              print('新闻列表 $data');
              if (data != null && data.isNotEmpty) {
                curPage += 1;
//                {"newslist":[{"author":"贝克街的天才","id":110756,"title":"Mars-java 2.2.2 发布，不需要容器的 Java Web 开发框架","type":4,"authorid":1248232,"pubDate":"2019-10-22 12:36:08","commentCount":6},{"author":"kaka996","id":110755,"title":"跨平台应用商店 Dapps 1.0.3 发布，增加 12306 抢票等多个应用","type":4,"authorid":3305311,"pubDate":"2019-10-22 10:11:31","commentCount":0},{"author":"若依开源","id":110754,"title":"若依后台管理系统 4.1 发布，新增多项功能 ","type":4,"authorid":1438828,"pubDate":"2019-10-22 09:52:24","commentCount":5},{"author":"mrbird","id":110753,"title":"FEBS Cloud 微服务权限系统 1.3 版本发布","type":4,"authorid":3690073,"pubDate":"2019-10-22 09:02:26","commentCount":2},{"author":"顾钧","id":110752,"title":"Milvus 0.5.0 发布，新增 Java SDK","type":4,"authorid":4209276,"pubDate":"2019-10-22 08:59:06","commentCount":1},{"author":"nobodyiam","id":110751,"title":"Apollo 1.5.0 发布，开源分布式配置中心"
                Map<String, dynamic> map = json.decode(data);
                print('当前页码map  $map');
                List cur = map['newslist'];
                print('map解析后 $cur');
                print('map解析后0 ${cur[0]}');
                print('map解析后author ${cur[0]['author']}');
                List<NewList> curPageList = new List();
                for (int i = 0; i < cur.length; i++) {
                  NewList newList = new NewList();
                  newList.id = cur[i]['id'];
                  newList.title = cur[i]['title'];
                  newList.author = cur[i]['author'];
                  newList.pubDate = cur[i]['pubDate'];
                  newList.authorid = cur[i]['authorid'];
                  newList.commentCount = cur[i]['commentCount'];
                  if(i%2==0){
                    newList.imgUrl='https://ss2.bdstatic.com/6Ot1bjeh1BF3odCf/it/u=932310317,3208700783&fm=74&app=80&f=PNG&size=f121,121?sec=1880279984&t=9b05419a680969090b2716d216e1dbe0';
                  }
                  curPageList.add(newList);
                  print('每条对象  ${newList.title}');
                }

                print('当前页码curPageList  $curPageList');
                if (!mounted) return;
                if (curPageList != null && curPageList.length > 0) {
                  setState(() {
                    _newsList.addAll(curPageList);
                  });
                }
              }
            });
          }
        });
      }
    });
  }
  _login(BuildContext context) async {
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => LoginWebPage(),
      ),
    );
    if (result != null && result == 'refresh') {
      //跳转过去后下一个界面约定子弹表示登录成功
      eventBus.fire(LoginEvent()); //登录成功通知loginEvent
    }
  }
  void _onLoading() async {
    _getNewsList();
    _refreshController.loadComplete();
  }

  void _onRefresh() async {
    curPage = 1;
    setState(() {
      _newsList.clear();
    });
    _getNewsList();
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    DataUtil.isLogin().then((isLogin) {
      if (!mounted) return;
      setState(() {
        this.isLogin = isLogin;
        if (this.isLogin) {
          _getNewsList();
        }
      });
    });
    eventBus.on<LoginEvent>().listen((event) {
      if (!mounted) return;
      setState(() {
        this.isLogin = true;
      });
      _getNewsList();
    });
    eventBus.on<LogoutEvent>().listen((event) {
      if (!mounted) return;
      setState(() {
        this.isLogin = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if(!this.isLogin){
      return Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
        Text('部分限制需登录才能查看'),
        InkWell(
          onTap: () async {
            await _login(context);
          },
          child: Text('登录'),
        ),
      ],);
    }
    if (_newsList == null || _newsList.length == 0) {
      return Center(
        child: CupertinoActivityIndicator(),
      );
    }
    return Scaffold(
//      appBar: AppBar(
//        title: Text('这个是上下拉刷新listview'),
//      ),
      body: SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("加载更多",style: TextStyle(color: Color(0x89657423)),);
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("Load Failed!Click retry!");
            } else if (mode == LoadStatus.canLoading) {
              body = Text("release to load more");
            } else {
              body = Text("没有更多数据了");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.builder(
          physics: BouncingScrollPhysics(),
          itemBuilder: (context, index) => Container(
            child: Center(
              child: NewListItemPull(newList: _newsList[index],),
            ),
          ),
          itemExtent: 100.0,
          itemCount: _newsList.length,
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
